package com.suyx.job.config;

import com.suyx.job.entity.JobInfo;
import com.suyx.job.job.ExecuteJob;
import com.suyx.job.service.IDeviceService;
import com.suyx.job.service.IEmailService;
import com.suyx.job.service.IJobInfoService;
import com.suyx.job.service.IJobLogService;
import com.suyx.job.service.IRoleInfoService;
import com.suyx.job.utils.SchedulerUtils;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/30 0030 17:47
 * @Description: 启动项目时 加载 数据库中的 任务
 */
@Component
public class SchedulerRunner implements CommandLineRunner {
    private SchedulerUtils scheduler;
    private IJobInfoService jobInfoServer;
    private RestTemplate restTemplate;
    private IEmailService emailService;
    private IJobLogService jobLogService;
    private IDeviceService deviceService ;
    private IRoleInfoService roleService ;
    private RedisUtils redisService;

    @Autowired
    public SchedulerRunner(SchedulerUtils scheduler, IJobInfoService jobInfoServer, RestTemplate restTemplate,
                           IEmailService emailService,RedisUtils redisService,
                           IJobLogService jobLogService,IDeviceService deviceService,IRoleInfoService roleService) {
        this.scheduler = scheduler;
        this.jobInfoServer = jobInfoServer;
        this.restTemplate = restTemplate;
        this.emailService = emailService;
        this.jobLogService = jobLogService;
        this.deviceService = deviceService;
        this.roleService = roleService;
        this.redisService = redisService;
    }

    @Override
    public void run(String... args) {
        List<JobInfo> jobInfos = jobInfoServer.findByJobStatus(0);
        ExecuteJob.init(restTemplate, emailService, jobLogService,deviceService,roleService,redisService);
        for (JobInfo jobInfo : jobInfos) {
            try {
                scheduler.addJob(jobInfo);
            } catch (SchedulerException | IllegalAccessException | InstantiationException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
